<?php

namespace Frieza\Modules\Activity\Controllers;

use App\Pockets\GridDataModel as pGridDataModel;
use Biz\cache\lottery\CSpringHomeGift;
use Biz\model\activity\Page as mPage;
use Biz\model\springHomeDecActivity\MSpringHomeDecProduct;
use Biz\model\springHomeDecActivity\MSpringHomeDecWinningRecord;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

class SpringHomeController
{


    public function list(Content $content, Request $request)
    {
        $tab = explode('/', parse_url($request->getRequestUri(), PHP_URL_PATH));
        $tab_sign = end($tab);
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 100);
        $offset = ($page - 1) * $pageSize;
        $offset = max($offset, 0);
        $tab = new Tab();
        $tab->addLink('中奖列表信息', 'list', $tab_sign == 'list');
        $tab->addLink('商品库存信息', 'goods', $tab_sign == 'goods');
        $tab->addLink('生成奖品池', 'pool', $tab_sign == 'pool');
        $tab->addLink('推送奖品', 'cache', $tab_sign == 'cache');
        $start = '20220310';
        $d = [];
        foreach (range(0, 30) as $add) {
            $d[] = date("Ymd", strtotime($start) + $add * 86400);
        }
        $grid = '';
        if ($tab_sign == 'list') {
            $where = [];
            if ($product_id = $request->input('product_id', '')) $where['product_id'] = explode(',', $product_id);
            if ($uid = $request->input('uid', '')) $where['uid'] = explode(',', $uid);
            if ($winning_date = $request->input('winning_date', '')) $where['winning_date'] = $winning_date;
            $list = MSpringHomeDecWinningRecord::dataSelect($where + ['ORDER' => ['id' => 'DESC'], 'LIMIT' => [
                $offset,
                $pageSize
            ]]);
            foreach ($list as &$v) {
                $address = $v['delivery_address'];
                $city = explode('|', $address);
                $address = $city[1] ?? '';
                $city = $city[0] ?? '';
                $city = explode(',', $city);
                $id = end($city);
                $v['info'] = $id ? (\Doraemon\tools\Area::locationId2full($id) . " $address") : $address;
            }
            $gridModel = new pGridDataModel($list, MSpringHomeDecWinningRecord::dataCount($where));
            $grid = Admin::grid($gridModel,
                function (Grid $grid) use ($gridModel) {
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->disableCreateButton();
                    $grid->paginate($gridModel->getPerPage());
                    $grid->filter(function (Grid\Filter $filter) {
                        // 去掉默认的id过滤器
                        $filter->disableIdFilter();

                        $filter->column(1 / 3, function (Grid\Filter $filter) {
                            $filter->equal('uid', '用户UID')->placeholder('多个uid,隔开');
                        });

                        $filter->column(1 / 3, function (Grid\Filter $filter) {
                            $filter->equal('product_id', '商品ID')->placeholder('多个商品ID,隔开');
                        });

                        $filter->column(1 / 3, function (Grid\Filter $filter) {
                            $filter->equal('winning_date', '中奖日期')->date();
                        });

                        //条件展开
                        $filter->expand();
                    });
                    $grid->column('id', '记录id');
                    $grid->column('uid', '用户UID');
                    $grid->column('product_id', '商品ID');
                    $grid->column('winning_date', '中奖日期');
                    $grid->column('create_time', '中奖时间');
                    $grid->column('is_reserve', '留资')->bool();
                    $grid->column('name', '姓名');
                    $grid->column('phone', '电话');
                    $grid->column('info', '收货地址');
                    $grid->disableActions();
                }
            );
        } elseif ($tab_sign == 'goods') {
            $lock = CSpringHomeGift::getLock();
            $lock = \Doraemon\tools\Msg2Admin::html('提示', implode('<br/>', ['间隔锁:'. $lock[0], '过期时间:' . $lock[1]]));
            $list = MSpringHomeDecProduct::dataSelect(['status' => 1]);
            $date = date('Ymd');
            foreach ($list as &$v) {
                $v['cache'] = CSpringHomeGift::giftCount($v['product_id'], $date);
            }
            $gridModel = new pGridDataModel($list);
            $grid = Admin::grid($gridModel,
                function (Grid $grid) use ($gridModel) {
                    $grid->disableExport();
                    $grid->disableRowSelector();
                    $grid->disableFilter();
                    $grid->disableCreateButton();
                    $grid->disablePagination();
                    $grid->column('product_id', '商品信息')->display(function() {
                        $display = [
                            '商品id:' . $this->product_id,
                            '商品类型:' . ($this->product_type == 1 ? '商品' : '服务'),
                        ];
                        return implode('<br/>', $display);
                    });
                    $grid->column('total', '初始总库存');
                    $grid->column('num', '剩余总库存');
                    $grid->column('cache', '缓存中库存');
                    $grid->disableActions();
                }
            );
            $grid = $lock . $grid->render();
        } elseif ($tab_sign == 'cache') {
            if ($request->getMethod() == 'POST') {
                try {
                    $date = $request->input('date');
                    $num = $request->input('num');
                    if (!$date) throw new \Exception('选择需要推送的奖池');
                    if (!$num) throw new \Exception('填写推送的数量');
                    $rs = CSpringHomeGift::pushGiftToList($date, $num);

                    $success = new MessageBag([
                        'title' => '推送成功 ' . $rs
                    ]);
                    return redirect('admin/activity/SpringHome/cache')->with(compact('success'));
                } catch (\Exception $e) {
                    $error = new MessageBag([
                        'title' => $e->getMessage()
                    ]);
                    return back()->with(compact('error'));
                }
            }
            $gifts = CSpringHomeGift::getGiftPool($d);
            $options = [];
            foreach ($gifts as $date => $list) {
                if ($list) $options[$date] = "$date 数量:" . count($list);
            }
            $form = new Form();
            $form->select('date', '选择奖池')->options($options)->required();
            $form->text('num', '推送数量')->default(1);
            $form->action('/admin/activity/SpringHome/cache');
            $grid = $form;
        }  elseif ($tab_sign == 'pool') {
            if ($request->getMethod() == 'POST') {
                try {
                    $date = $request->input('date');
                    if (empty($date)) throw new \Exception('日期为空');
                    $date = date('Ymd', strtotime($date));
                    $product = $request->input('product');
                    $shuffle = $request->input('shuffle');
                    $gifts = explode(',', $product);
                    if (empty($gifts)) throw new \Exception('奖品为空');
                    if ($shuffle) shuffle($gifts);
                    CSpringHomeGift::generateGiftPool($date, $gifts);
                    $success = new MessageBag([
                        'title' => '生成奖品池成功'
                    ]);
                    return redirect('admin/activity/SpringHome/pool')->with(compact('success'));
                } catch (\Exception $e) {
                    $error = new MessageBag([
                        'title' => $e->getMessage()
                    ]);
                    return back()->with(compact('error'));
                }
            }
            $html = ['只能追加奖品'];

            $gifts = CSpringHomeGift::getGiftPool($d);
            foreach ($gifts as $date => $value) {
                if (!empty($value)) $html[] = "日期$date : " . implode(',', $value);
            }
            $form = new Form();
            $form->date('date', '奖池日期');
            $form->radio('shuffle', '打乱')->options([1 => '是', 0 => '否'])->default(1);
            $form->textarea('product', '奖品池')->placeholder('多个奖品,分隔');
            $form->action('/admin/activity/SpringHome/pool');
            $info = \Doraemon\tools\Msg2Admin::html('提示', implode('<br/>', $html), 'warning');
            $grid = $info . $form->render();
        }

        return $content
            ->header('春季家装节')
            ->body($tab)
            ->row($grid)
            ;
    }

    private function drop($request)
    {
        if ($request->getMethod() == 'POST') {
            try {
                $date = $request->input('date');
                $date = date('Ymd', strtotime($date));
                $product = $request->input('product');
                $gifts = explode(',', $product);
                $temp = [];
                foreach ($gifts as $gift) {
                    $temp[$gift] = isset($temp[$gift]) ? $temp[$gift] + 1 : 1;
                }
                foreach ($temp as $product_id => $value) {
                    CSpringHomeGift::generateGift($date . "_" . $product_id, range(1, $value));
                }
                $success = new MessageBag([
                    'title' => '生成奖品池成功'
                ]);
                return redirect('admin/activity/SpringHome/cache')->with(compact('success'));
            } catch (\Exception $e) {
                $error = new MessageBag([
                    'title' => $e->getMessage()
                ]);
                return back()->with(compact('error'));
            }
        }
        $form = new Form();
        $form->date('date', '奖池日期');
        $form->textarea('product', '奖品池')->placeholder('多个奖品,分隔');
        $grid = $form;
    }

}